// pages/regimental-commander/store-closure/store-closure.js
import Toast from '../../../dist/toast/toast'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startDate: '',
    endDate: '',
    datePickerShow: false,
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    currentDateType: '',
    stopTipsText: '',
    stopReceivingDate: [],
    stopReceivingValue: '',
    stopReceivingShow: false,
    beforeReceive:{
      break_date_before_is_receive1: 1,
      break_date_before_is_receive2: 1,
      break_date_before_is_receive13: 1
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    closureReason: '',
    closureReasonText: '',
    reasonShow: false,
    reasonAction: [
      { name: '近期无法收货' },
      { name: '业务繁忙，人手不够' },
      { name: '暂时无法冷藏/冷冻商品' },
      { name: '暂时没有地方存储商品' },
      { name: '司机近期无法送货' },
      { name: '司机引导歇业' },
      { name: '不想继续开店了' },
      { name: '其他' }
    ]
  },

  /**
   * 显示时间选择
   * @param {Object} e 
   */
  showDatePicker: function(e) {
    const { dateType } = e.currentTarget.dataset
    if (dateType == 'end' && !this.data.startDate) {
      Toast('请先选择歇业开始日期')
      return false
    }
    this.setDatetRange(dateType)
    this.setData({
      currentDateType: dateType,
      datePickerShow: true
    })
  },

  /**
   * 隐藏时间选择
   */
  hideDatePicker: function () {
    this.setData({
      datePickerShow: false
    })
  },

  /**
   * 时间选择确定
   * @param {Object} e 
   */
  pickerConfirm: function(e) {
    const timeStamp = e.detail
    const inputValue = new Date(timeStamp).toLocaleDateString()
    const bar = this.data.currentDateType == 'end' ? 'endDate' : 'startDate'
    this.setData({
      [bar]: inputValue
    })
    this.hideDatePicker()
    // 设置开始日期
    if (this.data.currentDateType == 'start') {
      // 1天的毫秒数
      const oneDay = 86400000
      const today = new Date()
      // 今天的毫秒(今天00:00:00)
      const todayMill = new Date(today.toLocaleDateString()).getTime()
      // 当下小时
      const hour = today.getHours()
      // 开始日期距今天的天数
      const distanceToday = (timeStamp - todayMill) / oneDay
      // 开始时间为3天后 || 17点前 开始时间为2天
      // 
      if (distanceToday > 3 || (hour < 17 && distanceToday > 2)) {
        this.setData({
          stopReceivingDate: []
        })
      } else {
        let dateArray =  []
        for (let i = 1; i < distanceToday; i++) {
          const date = new Date(timeStamp - i*oneDay)
          dateArray.push({
            text: `${date.getMonth() + 1}月${date.getDate()}日`,
            date: date.toLocaleDateString(),
            field: 'break_date_before_is_receive' + i
          })
        }
        this.setData({
          stopReceivingDate: dateArray.reverse()
        })
      }
      // 开始日期的前一天
      const preDate = new Date(timeStamp - oneDay)
      this.setData({
        stopReceivingValue: '',
        beforeReceive: {
          break_date_before_is_receive1: 1,
          break_date_before_is_receive2: 1,
          break_date_before_is_receive3: 1
        },
        endDate: '',
        stopTipsText: `门店将于${preDate.getFullYear()}年${preDate.getMonth() + 1}月${preDate.getDate()}日起不支持用户下单` 
      })
    }
  },

  /**
   * 日期改变
   * @param {Object} e 
   */
  onInput(e) {
    this.setData({
      currentDate: e.detail,
    });
  },

  /**
   * 显示动作面板
   * @param {Object} e 
   */
  showActionSheet: function(e) {
    const type = e.currentTarget.dataset.sheetType
    this.setData({
      [type]: true
    })
  },

  /**
   * 隐藏动作面板
   * @param {Object} e 
   */
  hideActionSheet: function(e) {
    const type = e.currentTarget.dataset.sheetType
    this.setData({
      [type]: false
    })
  },

    /**
   * 动作面板选中
   * @param {Object} e 
   */
  actionSheetSelected: function(e) {
    const { item, sheetType, formType } = e.currentTarget.dataset
    this.setData({
      [formType]: item,
      [sheetType]: false
    })
    if (formType == 'closureReason') {
      this.setData({
        closureReasonText: '',
      })
    }
  },

  /**
   * 设置日期范围
   * @param {String} dateType 开始/结束日期
   */
  setDatetRange: function(dateType = '') {
    if (!dateType) {
      return
    }
    const oneDay = 24 * 60 * 60 * 1000
    const today = new Date()
    let min = null
    let max = null
    // 开始时间范围
    if (dateType == 'start') {
      // 当前小时
      const hour = new Date().getHours() 
      // 17点前2天后开始，17点后3天后开始
      const startDay = hour < 17 ? 2 : 3
      const startRange = new Date(today.getTime() + (startDay * oneDay))
      // 结束日期为开始日期后100天
      const endRange = new Date(today.getTime() + (startDay * oneDay) + (100 * oneDay))
      min = new Date(startRange.toLocaleDateString()).getTime()
      max = new Date(endRange.toLocaleDateString()).getTime()
    } else if(dateType == 'end') {
      min = new Date(this.data.startDate).getTime()
      // 最大日期范围为开始日期后14天
      max = new Date(min + 14 * oneDay).getTime()
    }
    this.setData({
      minDate: min,
      maxDate: max
    })
  },

  /**
   * 是否可收货选中
   * @param {Object} e 
   */
  stopReceivingSelected: function(e) {
    const { value, text, field } = e.currentTarget.dataset
    // 只有一天
    if (this.data.stopReceivingDate.length == 1) {
      this.setData({
        beforeReceive: {
          break_date_before_is_receive1: value,
          break_date_before_is_receive2: 2,
          break_date_before_is_receive3: 2
        }
      })
    }
    // 选项为全部
    else if (field == 'all') {
      this.setData({
        beforeReceive: {
          break_date_before_is_receive1: value,
          break_date_before_is_receive2: value,
          break_date_before_is_receive3: value
        }
      })
    } else {
      let obj = {
        break_date_before_is_receive1: 2,
        break_date_before_is_receive2: 2,
        break_date_before_is_receive3: 2
      }
      obj[field] = 1
      this.setData({
        beforeReceive: obj
      })
    }
    this.setData({
      stopReceivingValue: text,
      stopReceivingShow: false
    })
  },

  /**
   * 提交申请
   */
  submitApplication: function() {
    const {
      startDate,
      endDate,
      stopReceivingDate,
      stopReceivingValue,
      closureReason,
      closureReasonText,
      beforeReceive,
    } = this.data
    if (!startDate) {
      wx.showToast({ title: '请选择歇业开始日期', icon: 'none' })
      return
    }
    if (!endDate) {
      wx.showToast({ title: '请选择歇业结束日期', icon: 'none' })
      return
    }
    if (stopReceivingDate.length && !stopReceivingValue) {
      let text = ''
      if (stopReceivingDate.length == 1) {
        text = stopReceivingDate[0].text
      } else {
        text = `${stopReceivingDate[0].text}-${stopReceivingDate[stopReceivingDate.length - 1].text}` 
      }
      wx.showToast({ title: `${text}您可以收货吗`, icon: 'none' })
      return
    }
    if (!closureReason) {
      wx.showToast({ title: `请选择歇业原因`, icon: 'none' })
      return
    }
    if (closureReason == '其他' && !closureReasonText) {
      wx.showToast({ title: `请输入歇业原因`, icon: 'none' })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    const parame = {
      break_date_start: startDate,
      break_date_end: endDate,
      break_reason: closureReason,
      break_desc: closureReasonText,
      break_date_before_is_receive1: beforeReceive.break_date_before_is_receive1,
      break_date_before_is_receive2: beforeReceive.break_date_before_is_receive2,
      break_date_before_is_receive3: beforeReceive.break_date_before_is_receive3
    }
    const url = app.getNetAddresss('plugin.package-deliver.frontend.DeliverBreak.add')
    app._postNetWork({
      url,
      data: parame,
      success: function(res) {
        wx.hideLoading()
        const { data } = res
        wx.showToast({
          icon: data.result == 1 ? '' : 'none',
          title: data.msg,
        })
        // 成功后跳转到团长首页
        if (data.result == 1) {
          wx.navigateTo({
            url: '/pages/regimental-commander/home/home',
          })
        }
      },
      fail: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 获取歇业状态
   */
  getClosureStatus: function() {
    const url = app.getNetAddresss('plugin.package-deliver.frontend.DeliverBreak.getBreakInfo')
    app._postNetWork({
      url,
      success: function(res) {
        console.log(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getClosureStatus()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})